<?php

class Confirm_sheetController extends CController
{
	const PAGE_SIZE=10;

	/**
	 * @var string specifies the default action to be 'list'.
	 */
	public $defaultAction='create';

	/**
	 * @var CActiveRecord the currently loaded data model instance.
	 */
	private $_model;
	
	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			array('application.filters.LoginFilter'),
			array('application.filters.AuthFilter'),
		);
	}

	/**
	 * Shows a particular model.
	 */
	public function actionShow(){	
		
		$model=$this->loadConfirm_sheet();
		$goods_models=$this->loadGoods_info();
		$deadhead_models=$this->loadDeadhead_info();
		$gas_models=$this->loadGas_info();
		$extra_models=$this->loadExtra_cost();
		$this->render('show',array('model'=>$model,'goods_models'=>$goods_models,'deadhead_models'=>$deadhead_models,
									'gas_models'=>$gas_models,'extra_models'=>$extra_models));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'show' page.
	 */
	public function actionCreate()
	{	
		if(!isset($_GET['aid'])){//由派车单导入
			echo '没有需确认的派车单信息!';
			$this->redirect(array('site/to_close','message'=>2));
		}
		
		$model=new Confirm_sheet;	
		$a_model=$this->appToConfirm($_GET['aid'],$model);
		if($a_model==false) $this->redirect(array('site/to_close','message'=>3));//导入的派车单不存在或已删除
		$goods_models=array();
		$a_goods_models=$this->a_goodsToC_goods($_GET['aid'],$goods_models);
		$deadhead_models=array();
		$a_deadhead_models=$this->a_deaheadToC_deahead($_GET['aid'],$deadhead_models);
		
		$gas_models=array(new Confirm_gas_fee);
		$deadhead_temp=new Confirm_deadhead_info;//提货空驶模板
		$extra_temp=new Confirm_extra_cost;//其他费用模板
		$extra_models=array();//建立空数组 可能不存在其他费用信息
		if(isset($_POST['Confirm_sheet']))
		{
			$deadheads=array();
			$extras=array();
			$goods=array();
			$gas=array();
			
			$model->attributes=$_POST['Confirm_sheet'];
			if(isset($_POST['goods']))//判断是否存在货物信息
				$goods=$_POST['goods'];
			else
				$goods_models=array();
				
			if(isset($_POST['gas']))//判断是否存在燃油信息
				$gas=$_POST['gas'];
			else
				$gas_models=array();	
				
			if(isset($_POST['deadhead']))//判断是否存在提货空驶信息
				$deadheads=$_POST['deadhead'];
				
			if(isset($_POST['extra']))//判断是否存在其他费用信息
				$extras=$_POST['extra'];	
				
			$create=true;
			foreach($goods as $n=>$val){
				$goods_model=new Confirm_goods_info;
				$goods_model->attributes=$val;
				$goods_models[$n]=$goods_model;
				$create=$goods_model->validate()==true?$create:false;
			}
			foreach($gas as $n=>$val){
				$gas_model=new Confirm_gas_fee;
				$gas_model->attributes=$val;
				$gas_models[$n]=$gas_model;
				$create=$gas_model->validate()==true?$create:false;
			}
			foreach($deadheads as $n=>$val){
				$deadhead_model=new Confirm_deadhead_info;
				$deadhead_model->attributes=$val;
				$deadhead_models[$n]=$deadhead_model;
				$create=$deadhead_model->validate()==true?$create:false;
			}
			foreach($extras as $n=>$val){
				$extra_model=new Confirm_extra_cost;
				$extra_model->attributes=$val;
				$extra_models[$n]=$extra_model;
				$create=$extra_model->validate()==true?$create:false;
			}
			
			if($model->loading_status==0){//判断重驶 还是制定空驶 如是重驶则将第一个货物信息始发、目的地赋予确认单始发、目的地
				$model->setScenario('heaven');
				$model->origin=$goods_models[0]->origin;
				$model->destination=$goods_models[0]->destination;
				$gas_fee=0;$gas_amount=0;//将所有油费金额总额存、油容积存入主表
				foreach($gas_models as $n=>$val){
					$gas_fee+=$val->cost;
					$gas_amount+=$val->amount;
				}
				$model->gas_fee=$gas_fee;
				$model->gas_amount=$gas_amount;
				$extra_cost=0;//将所有其他费用金额存入主表
				foreach($extra_models as $n=>$val){
					$extra_cost+=$val->cost;
				}
				$model->extra_cost=$extra_cost;
			}
			else{//指定空驶 将总里程数值赋给相应的标准油耗总里程
				$model->actual_front_mileage=0;
				$model->actual_empty_mileage=0;
				$model->actual_light_mileage=0;
				$model->actual_heavy_mileage=0;
				$fuel='actual_'.substr($model->fuel_name,0,5).'_mileage';
				$model->$fuel=$model->mileage;
				$model->setScenario('empty');
			}
			$create=$model->validate()==true?$create:false;//验证事故信息
			if($create){//全部验证通过  添加数据库 启动事务
				$tran=$model->getDbConnection()->beginTransaction();
				try{
					$model->save(false);
					foreach($goods_models as $val){
						$val->fk_confirm_id=$model->id;
						$val->save(false);
					}
					foreach($gas_models as $val){
						$val->fk_confirm_id=$model->id;
						$val->save(false);
					}
					foreach($deadhead_models as $val){
						$val->fk_confirm_id=$model->id;
						$val->save(false);
					}
					foreach($extra_models as $val){
						$val->fk_confirm_id=$model->id;
						$val->save(false);
					}
					
					//添加成功 将派车单删除
					$a_model->state=1;
					$a_model->save(false);
					foreach($a_goods_models as $val){
						$val->state=1;
						$val->save(false);
					}
					foreach($a_deadhead_models as $val){
						$val->state=1;
						$val->save(false);
					}
					
					$tran->commit();
				}
				catch(Exception $e){
					$tran->rollBack();
					throw $e;
				}
				//$this->render('show',array('model'=>$model,'goods_models'=>$goods_models,'deadhead_models'=>$deadhead_models,'ret'=>'create','info'=>'添加成功！派车单号:'.$model->appointment_no));
				//return;
				$this->redirect(array('show','id'=>$model->id,'ret'=>'site/to_close','ok'=>'0'));
			}
		}
		$this->render('create',array('model'=>$model,'goods_models'=>empty($goods_models)?array(new Confirm_goods_info):$goods_models,'deadhead_temp'=>$deadhead_temp,
					  'deadhead_models'=>$deadhead_models,'gas_models'=>$gas_models,'extra_temp'=>$extra_temp,
					  'extra_models'=>$extra_models,));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'show' page.
	 */
	public function actionUpdate()
	{
		$model=$this->loadConfirm_sheet();
		$goods_models=$this->loadGoods_info();
		$gas_models=$this->loadGas_info();
		$deadhead_models=$this->loadDeadhead_info();
		$deadhead_temp=new Confirm_deadhead_info;//提货空驶模板
		$extra_models=$this->loadExtra_cost();
		$extra_temp=new Confirm_extra_cost;//提货空驶模板
		
		if(isset($_POST['Confirm_sheet'])){//将所有费用赋值 并且验证
			$deadheads=array();
			$extras=array();
			$goods=array();
			$gas=array();
			$model->attributes=$_POST['Confirm_sheet'];
			
			if(isset($_POST['goods']))//判断是否存在货物信息
				$goods=$_POST['goods'];
				
			if(isset($_POST['gas']))//判断是否存在油费信息
				$gas=$_POST['gas'];	
				
			if(isset($_POST['deadhead']))//判断是否存在提货空驶信息
				$deadheads=$_POST['deadhead'];
			
			if(isset($_POST['extra']))//判断是否存在提货空驶信息
				$extras=$_POST['extra'];	
				
			$goods_sum=count($goods);
			$goods_models_sum=count($goods_models);
			$update=true;
			if($goods_sum==$goods_models_sum){//费用信息数量没变
				foreach($goods as $n=>$val){
					$goods_model=$goods_models[$n];
					$goods_model->attributes=$val;
					$update=$goods_model->validate()==true?$update:false;
				}
			}
			else if($goods_sum>$goods_models_sum){//费用信息数量增加
				foreach($goods as $n=>$val){
					$goods_model=isset($goods_models[$n])?$goods_models[$n]:new Confirm_goods_info;
					$goods_model->attributes=$val;
					$update=$goods_model->validate()==true?$update:false;
					$goods_models[$n]=$goods_model;
				}
			}
			else if($goods_sum<$goods_models_sum){//费用信息数量减少
				foreach($goods_models as $n=>$val){
					if(isset($goods[$n])){
						$val->attributes=$goods[$n];
						$update=$val->validate()==true?$update:false;
					}
					else
						$val->state=1;
				}
			}
			$gas_sum=count($gas);
			$gas_models_sum=count($gas_models);
			$update=true;
			if($gas_sum==$gas_models_sum){//费用信息数量没变
				foreach($gas as $n=>$val){
					$gas_model=$gas_models[$n];
					$gas_model->attributes=$val;
					$update=$gas_model->validate()==true?$update:false;
				}
			}
			else if($gas_sum>$gas_models_sum){//费用信息数量增加
				foreach($gas as $n=>$val){
					$gas_model=isset($gas_models[$n])?$gas_models[$n]:new Confirm_gas_fee;
					$gas_model->attributes=$val;
					$update=$gas_model->validate()==true?$update:false;
					$gas_models[$n]=$gas_model;
				}
			}
			else if($gas_sum<$gas_models_sum){//费用信息数量减少
				foreach($gas_models as $n=>$val){
					if(isset($gas[$n])){
						$val->attributes=$gas[$n];
						$update=$val->validate()==true?$update:false;
					}
					else
						$val->state=1;
				}
			}
			$deadheads_sum=count($deadheads);
			$deadhead_models_sum=count($deadhead_models);
			if($deadheads_sum==$deadhead_models_sum){//费用信息数量没变
				foreach($deadheads as $n=>$val){
					$deadhead_model=$deadhead_models[$n];
					$deadhead_model->attributes=$val;
					$update=$deadhead_model->validate()==true?$update:false;
				}
			}
			else if($deadheads_sum>$deadhead_models_sum){//费用信息数量增加
				foreach($deadheads as $n=>$val){
					$deadhead_model=isset($deadhead_models[$n])?$deadhead_models[$n]:new Confirm_deadhead_info;
					$deadhead_model->attributes=$val;
					$update=$deadhead_model->validate()==true?$update:false;
					$deadhead_models[$n]=$deadhead_model;
				}
			}
			else if($deadheads_sum<$deadhead_models_sum){//费用信息数量减少
				foreach($deadhead_models as $n=>$val){
					if(isset($deadheads[$n])){
						$val->attributes=$deadheads[$n];
						$update=$val->validate()==true?$update:false;
					}
					else
						$val->state=1;
				}
			}
			$extras_sum=count($extras);
			$extra_models_sum=count($extra_models);
			if($extras_sum==$extra_models_sum){//费用信息数量没变
				foreach($extras as $n=>$val){
					$extra_model=$extra_models[$n];
					$extra_model->attributes=$val;
					$update=$extra_model->validate()==true?$update:false;
				}
			}
			else if($extras_sum>$extra_models_sum){//费用信息数量增加
				foreach($extras as $n=>$val){
					$extra_model=isset($extra_models[$n])?$extra_models[$n]:new Confirm_extra_cost;
					$extra_model->attributes=$val;
					$update=$extra_model->validate()==true?$update:false;
					$extra_models[$n]=$extra_model;
				}
			}
			else if($extras_sum<$extra_models_sum){//费用信息数量减少
				foreach($extra_models as $n=>$val){
					if(isset($extras[$n])){
						$val->attributes=$extras[$n];
						$update=$val->validate()==true?$update:false;
					}
					else
						$val->state=1;
				}
			}
			if($model->loading_status==0){
				$model->setScenario('heaven');
				$model->origin=$goods_models[0]->origin;
				$model->destination=$goods_models[0]->destination;
				$gas_fee=0;$gas_amount=0;//将所有油费金额总额、容积存入主表
				foreach($gas_models as $n=>$val){
					if($val->state==0){
						$gas_fee+=$val->cost;
						$gas_amount+=$val->amount;
					}
				}
				$model->gas_fee=$gas_fee;
				$model->gas_amount=$gas_amount;
				$extra_cost=0;//将所有其他费用金额存入主表
				foreach($extra_models as $n=>$val){
					if($val->state==0)
						$extra_cost+=$val->cost;
				}
				$model->extra_cost=$extra_cost;
			}
			else{
				$model->actual_front_mileage=0;
				$model->actual_empty_mileage=0;
				$model->actual_light_mileage=0;
				$model->actual_heavy_mileage=0;
				$fuel='actual_'.substr($model->fuel_name,0,5).'_mileage';
				$model->$fuel=$model->mileage;
				$model->setScenario('empty');
			}
			$update=$model->validate()==true?$update:false;//验证信息
			if($update){//全部验证通过  添加数据库
				$tran=$model->getDbConnection()->beginTransaction();
				try{
					$model->save(false);
					foreach($goods_models as $n=>$val){
						$val->fk_confirm_id=$model->id;
						$val->save(false);
						if($val->state==1) unset($goods_models[$n]);
					}
					foreach($gas_models as $n=>$val){
						$val->fk_confirm_id=$model->id;
						$val->save(false);
						if($val->state==1) unset($gas_models[$n]);
					}
					foreach($deadhead_models as $n=>$val){
						$val->fk_confirm_id=$model->id;
						$val->save(false);
						if($val->state==1) unset($deadhead_models[$n]);
					}
					foreach($extra_models as $n=>$val){
						$val->fk_confirm_id=$model->id;
						$val->save(false);
						if($val->state==1) unset($extra_models[$n]);
					}
					$tran->commit();
				}
				catch(Exception $e){
					$tran->rollBack();
					throw $e;
				}
				//$this->render('show',array('model'=>$model,'goods_models'=>$goods_models,'deadhead_models'=>$deadhead_models,'ret'=>'admin','info'=>'更新成功！'));
				//return;
				$this->redirect(array('show','id'=>$model->id,'ret'=>'admin','ok'=>'1')+$_GET);
			}
		}
		$this->render('update',array('model'=>$model,'goods_models'=>empty($goods_models)?array(new Confirm_goods_info):$goods_models,
		'gas_models'=>empty($gas_models)?array(new confirm_gas_fee):$gas_models,'deadhead_temp'=>$deadhead_temp,'deadhead_models'=>$deadhead_models,
		'extra_temp'=>$extra_temp,'extra_models'=>$extra_models));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'list' page.
	 */
	public function actionDelete()
	{
		if(isset($_GET['id'])){
			$confirm_sheet=Confirm_sheet::model();
			$goods=Confirm_goods_info::model();
			$deadhead=Confirm_deadhead_Info::model();
			$tran=$confirm_sheet->getDbConnection()->beginTransaction();
			try{
				$confirm_sheet->updateByPk($_GET['id'],array('state'=>1));
				$goods->updateAll(array('state'=>1),array('condition'=>'fk_confirm_id='.$_GET['id']));
				$deadhead->updateAll(array('state'=>1),array('condition'=>'fk_confirm_id='.$_GET['id']));
				$tran->commit();
			}
			catch(Exception $e){
				$tran->rollBack();
				throw $e;
			}
			unset($_GET['id']);
			$this->redirect(array('admin')+$_GET);
		}
		else
			throw new CHttpException(400,'无法获得要删除的信息ID!');
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{	
		$this->search(false);
	}
	
	public function actionSearch(){
		$this->search();
	}
	
	private function search($method=true){
		$criteria=new CDbCriteria();
		$criteria->join='LEFT JOIN confirm_goods_info as goods ON goods.fk_confirm_id=confirm_sheet.id and goods.state=0';
		$criteria->select='goods.consignor_name as consignor_name,goods.consignee_name as consignee_name,
				goods.goods_name as goods_name,goods.demand_deliver_time as goods_demand_deliver_time,confirm_sheet.*';
		$criteria->group='confirm_sheet.id';
		$criteria->addCondition('confirm_sheet.state=0');
		$blur=true;
		if(Yii::app()->getRequest()->isPostRequest){
			if(isset($_POST['keys'])){//页面传来的搜索关键字数组
				$_GET['keys']=$_POST['keys'];
			}
		}
		if(isset($_GET['keys'])){
			if(isset($_GET['keys']['blur'])&&$_GET['keys']['blur']=='0') $blur=false;
			foreach($_GET['keys'] as $key=>$val){
				if(trim($val)=='')
					unset($_GET['keys'][$key]);
				else if($key=='s_date'){//时间查询
					$criteria->addCondition("date_format(confirm_sheet.appointment_time,'%Y-%m')='{$val}'");
				}
				else if($key=='amount_cost'){//时间查询
					if($val==1)
						$criteria->addCondition("confirm_sheet.total_amount>0 or confirm_sheet.total_cost>0");
					else
						$criteria->addCondition("confirm_sheet.total_amount=0 and confirm_sheet.total_cost=0");	
				}
				/*
				else if($key=='e_date'){//时间查询  
					$t=date('Y-m-d',strtotime($val." +1days"));
					$criteria->addCondition("goods.demand_deliver_time<'{$t}' or (isnull(goods.id) and confirm_sheet.appointment_time<'{$t}')");
				}*/	
				else if($key!='blur'){//按照模糊或精确查询
					$blur?$criteria->addSearchCondition($key,$val):$criteria->addCondition("{$key}='{$val}'");
				}
			}
		}
		
		if(isset($_GET['excel']))//输出excel
			$this->toExcel($criteria);
		else	//转入查询/修改页面
			$this->toAdminPage($criteria,$method);
		
	}
	
	public function toAdminPage($criteria,$method){
		$model=Confirm_sheet::model();
		$command=$model->getCommandBuilder();//因group by 查询准确记录数量
		$sql="select count(t.id) from( select confirm_sheet.id FROM confirm_sheet";
		$sql=$command->applyJoin($sql,$criteria->join);
		$sql=$command->applyCondition($sql,$criteria->condition);
		$sql=$command->applyGroup($sql,$criteria->group).") as t";//echo $sql;
		$pages=new CPagination($model->countBySql($sql,$criteria->params));
		
		$pages->pageSize=Yii::app()->params['page_size']['confirm_sheet'];
		$pages->applyLimit($criteria);
		
		$sort=new CSort('Confirm_sheet');
		$sort->defaultOrder='confirm_no desc';
		$sort->attributes=array_merge($model->attributeNames(),array('truck_plate_no','board_plate_no','type',
		'driver1_name','consignor_name','consignee_name','goods_name','goods_demand_deliver_time','origin','destination'));
		$sort->applyOrder($criteria);

		$models=$model->findAll($criteria);

		$this->render('admin',array(
			'models'=>$models,
			'pages'=>$pages,
			'sort'=>$sort,
			'search'=>$method,
		));
	}
	
	public function toExcel($criteria){
		$model=Confirm_sheet::model();
		$sort=new CSort('Confirm_sheet');
		$sort->defaultOrder='confirm_no desc';
		$sort->attributes=array_merge($model->attributeNames(),array('truck_plate_no','board_plate_no','type',
		'driver1_name','consignor_name','consignee_name','goods_name','goods_demand_deliver_time','origin','destination'));
		$sort->applyOrder($criteria);
		$models=$model->findAll($criteria);

		$atrr_names=$model->attributeLabels();
		$excel_names=$model->excelAttributes();$end_cell=end($excel_names);
		$tab_name='确认单';
		
		require_once './protected/extensions/excel/PHPExcel.php';
		require_once './protected/extensions/excel/PHPExcel/IOFactory.php';
		$objPHPExcel = new PHPExcel();
		$objPHPExcel->setActiveSheetIndex(0)->setTitle($tab_name);
		$objPHPExcel->getActiveSheet()->mergeCells('A1:'.$end_cell[0].'1');
		$objPHPExcel->getActiveSheet()->setCellValue('A1',$tab_name);
		$objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(15);
		$objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal('center');
		$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(5);
		$objPHPExcel->getActiveSheet()->setCellValue('A2','序号');
		$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(5);
		$objPHPExcel->getActiveSheet()->freezePane('A3');//标题栏 冻结窗口
		foreach($excel_names as $attr=>$val){//创建标题
			$objPHPExcel->getActiveSheet()->setCellValue($val[0].'2',$atrr_names[$attr]);
			$objPHPExcel->getActiveSheet()->getColumnDimension($val[0])->setWidth($val[1]);
		}
		$row_index=3;//行索引 数据从3开始 例如A从A3开始添加数据
		foreach($models as $n=>$model){
			$objPHPExcel->getActiveSheet()->setCellValue('A'.($n+$row_index),$n+1);
			foreach($excel_names as $attr=>$val){//双循环，根据model内设置进行数据导出
				$value=$model->$attr;
				if(isset($val[2]))//值->字符串 转换
					$value=$model->$val[2]();
				$sheet=$objPHPExcel->getActiveSheet()->setCellValue($val[0].($n+$row_index),$value);
				if(isset($val['format']))//数值太大，按照常规数值显示
					$sheet->getStyle($val[0].($n+$row_index))->getNumberFormat()->setFormatCode($val['format']);
			}
		}
		header('Content-Type: application/vnd.ms-excel');
		header('Content-Disposition: attachment;filename='.iconv("utf-8", "gb2312", $tab_name.'.xls'));
		header('Cache-Control: max-age=0');
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		$objWriter->save('php://output'); 
	}
	
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the primary key value. Defaults to null, meaning using the 'id' GET variable
	 */
	public function loadConfirm_sheet($id=null)
	{
		if($id!==null || isset($_GET['id'])){
				$criteria=new CDbCriteria();
				$criteria->join='INNER JOIN trucks ON trucks.id=confirm_sheet.fk_truck_id
								 INNER JOIN truck_type_info as tti ON tti.id=trucks.fk_type_id';
				$criteria->select='tti.type_name as truck_type,tti.compute_ratio as truck_type_ratio,confirm_sheet.*';
				$criteria->addCondition('confirm_sheet.id='.($id!==null ? $id : $_GET['id']));
				$this->_model=Confirm_sheet::model()->find($criteria);
			}
		return $this->_model;
	}

	public function loadGoods_info($id=null)
	{		
		if($id!==null || isset($_GET['id']))
			$criteria=new CDbCriteria();
			$criteria->addCondition('fk_confirm_id='.($id!==null ? $id : $_GET['id']));
			$criteria->addCondition('state=0');
			$models=Confirm_goods_info::model()->findAll($criteria);
		return $models;
	}
	
	public function loadGas_info($id=null)
	{		
		if($id!==null || isset($_GET['id']))
			$criteria=new CDbCriteria();
			$criteria->addCondition('fk_confirm_id='.($id!==null ? $id : $_GET['id']));
			$criteria->addCondition('state=0');
			$models=Confirm_gas_fee::model()->findAll($criteria);
		return $models;
	}
	
	public function loadExtra_cost($id=null)
	{		
		if($id!==null || isset($_GET['id']))
			$models=Confirm_extra_cost::model()->findAllByAttributes(array('fk_confirm_id'=>($id!==null ? $id : $_GET['id']),'state'=>0));
		return $models;
	}
	
	public function loadDeadhead_info($id=null)
	{		
		if($id!==null || isset($_GET['id']))
			$models=Confirm_deadhead_info::model()->findAllByAttributes(array('fk_confirm_id'=>($id!==null ? $id : $_GET['id']),'state'=>0));
		return $models;
	}
	
	public function actionCheckTruckFuel(){
		if(Yii::app()->request->isAjaxRequest){
			if(isset($_POST['truck_id'])){
				$time=$_POST['time'].'-01';
				$b=Fuel_consumption::model()->exists(array('condition'=>'fk_truck_id=:truck_id and state=0'." and '$time' BETWEEN  effect_date and lapse_date",
											'params'=>array(':truck_id'=>$_POST['truck_id'])));
				echo $b?1:0;
			}			
		}
	}
	
	public function actionCheckTruckMerit(){
		if(Yii::app()->request->isAjaxRequest){
			if(isset($_POST['truck_id'])){
				$time=$_POST['time'].'-01';
				$b=Merit_pay_ratio::model()->exists(array('condition'=>'fk_truck_id=:truck_id and state=0'." and '$time' BETWEEN  effect_date and lapse_date",
											'params'=>array(':truck_id'=>$_POST['truck_id'])));
				echo $b?1:0;
			}			
		}
	}
	
	private function appToConfirm($aid,$c_model){
		
		$criteria=new CDbCriteria();
		$criteria->join='INNER JOIN trucks ON trucks.id=truck_appointment.fk_truck_id
						 LEFT JOIN trucks as board ON board.id=truck_appointment.fk_board_id
						 INNER JOIN truck_type_info as tti ON tti.id=truck_appointment.fk_type_id
						 INNER JOIN truck_type_info as tti1 ON tti1.id=trucks.fk_type_id
						 INNER JOIN drivers as driver1 ON driver1.id=truck_appointment.fk_driver1_id
						 LEFT JOIN drivers as driver2 ON driver2.id=truck_appointment.fk_driver2_id
						 LEFT JOIN fuel_consumption as fuel ON fuel.fk_truck_id=truck_appointment.fk_truck_id and fuel.state=0 
						 and date_format(truck_appointment.business_time,"%Y-%m-01") between fuel.effect_date and fuel.lapse_date ';
		$criteria->select='trucks.plate_no as truck_plate_no,board.plate_no as board_plate_no,tti.type_name as type,tti.compute_ratio as compute_ratio,
				driver1.name as driver1_name,driver2.name as driver2_name,driver1.mobile_no as driver1_mobile,
				driver2.mobile_no as driver2_mobile,fuel.front_driving as front_fuel,fuel.light_driving as light_fuel,
				fuel.empty_driving as empty_fuel,fuel.heavy_driving as heavy_fuel,tti1.type_name as truck_type,
				tti1.compute_ratio as truck_type_ratio,truck_appointment.*';
		$criteria->addCondition('truck_appointment.id='.$aid);
		$a_model=Truck_appointment::model()->find($criteria);
		if(empty($a_model)||$a_model->state!=0) return false;
		$c_model->loading_status=$a_model->loading_status;
		$c_model->fk_truck_id=$a_model->fk_truck_id;
		$c_model->truck_plate_no=$a_model->truck_plate_no;
		$c_model->board_plate_no=$a_model->board_plate_no;
		$c_model->type=$a_model->type;
		$c_model->truck_type=$a_model->truck_type;
		$c_model->truck_type_ratio=$a_model->truck_type_ratio;
		$c_model->compute_ratio=$a_model->compute_ratio;
		$c_model->driver1_name=$a_model->driver1_name;
		$c_model->driver2_name=$a_model->driver2_name;
		$c_model->driver1_mobile=$a_model->driver1_mobile;
		$c_model->driver2_mobile=$a_model->driver2_mobile;
		$c_model->confirm_no=$a_model->appointment_no;
		$c_model->front_fuel=$a_model->front_fuel;
		$c_model->empty_fuel=$a_model->empty_fuel;
		$c_model->light_fuel=$a_model->light_fuel;
		$c_model->heavy_fuel=$a_model->heavy_fuel;
		$c_model->actual_front_fuel=$a_model->front_fuel;
		$c_model->actual_empty_fuel=$a_model->empty_fuel;
		$c_model->actual_light_fuel=$a_model->light_fuel;
		$c_model->actual_heavy_fuel=$a_model->heavy_fuel;
		$c_model->mileage=$a_model->mileage;
		$c_model->driving_circuit=$a_model->driving_circuit;
		$c_model->amount_kind=$a_model->amount_kind;
		$c_model->special_reasons=$a_model->special_reasons;
		$c_model->advance_payment=$a_model->advance_payment;
		$c_model->balance=$a_model->balance;
		$c_model->total_amount=$a_model->total_amount;
		$c_model->remark=$a_model->remark;
		$c_model->gas_fee=$a_model->gas_fee;
		$c_model->gas_amount=$a_model->gas_amount;
		$c_model->bridge_charge=$a_model->bridge_charge;
		$c_model->origin=$a_model->origin;
		$c_model->destination=$a_model->destination;
		$c_model->fuel_name=$a_model->fuel_name;
		$c_model->extra_cost=$a_model->extra_cost;
		$c_model->total_cost=$a_model->total_cost;
		$c_model->driver_prepaid=$a_model->driver_prepaid;
		$c_model->prepaid_place=$a_model->prepaid_place;
		$c_model->appointment_time=$a_model->business_time;
		return $a_model;
	}
	
	private function a_goodsToC_goods($aid,&$c_goods_models){
		$criteria=new CDbCriteria();//INNER JOIN goods_name as g_name ON g_name.id=goods_info.fk_goods_name_id
		$criteria->join='INNER JOIN consignor_info as consignor ON consignor.id=goods_info.fk_consignor_id
						 INNER JOIN consignee_info as consignee ON consignee.id=goods_info.fk_consignee_id
						 INNER JOIN path ON path.id=goods_info.fk_path_id';
		$criteria->select='consignor.name as consignor_name,consignee.name as consignee_name,
		path.loading_place as origin,path.pod_place as destination,path.mileage as path_mileage,path.perform_pay as driver_salary,
		goods_info.*';
		$criteria->addCondition('goods_info.fk_appointment_id='.$aid);
		$criteria->addCondition('goods_info.state=0');
		$a_goods_models=Goods_info::model()->findAll($criteria);
		foreach($a_goods_models as $key=>$val){
			$c_goods=new Confirm_goods_info;
			$c_goods->consignor_name=$val->consignor_name;
			$c_goods->actual_consignee=$val->consignee_name;
			$c_goods->consignee_name=$val->consignee_name;
			$c_goods->consignor_link_name=$val->consignor_link_name;
			$c_goods->consignor_link_tel=$val->consignor_link_tel;
			$c_goods->consignee_link_name=$val->consignee_link_name;
			$c_goods->consignee_link_tel=$val->consignee_link_tel;
			$c_goods->goods_name=$val->goods_name;
			$c_goods->fk_consignor_id=$val->fk_consignor_id;
			$c_goods->fk_consignee_id=$val->fk_consignee_id;
			$c_goods->origin=$val->origin;
			$c_goods->destination=$val->destination;
			$c_goods->path_mileage=$val->path_mileage;
			$c_goods->driver_salary=$val->driver_salary;
			$c_goods->fuel_name=$val->fuel_name;
			$c_goods->amount=$val->amount;
			$c_goods->unit_name=$val->unit_name;
			$c_goods->pack_type=$val->pack_type;
			$c_goods->time_costing=$val->time_costing;
			$c_goods->lift_kind=$val->lift_kind;
			$c_goods->loading_place=$val->loading_place;
			$c_goods->pod_place=$val->pod_place;
			$c_goods->demand_deliver_time=$val->demand_deliver_time;
			$c_goods->demand_arrival_time=$val->demand_arrival_time;
			$c_goods->actual_arrival_time=$val->demand_arrival_time;
			$c_goods->driving_circuit=$val->driving_circuit;
			$c_goods_models[]=$c_goods;
		}
		return $a_goods_models;
	}
	private function a_deaheadToC_deahead($aid,&$c_deadhead_models){
		$criteria=new CDbCriteria();
		$criteria->addCondition('fk_appointment_id='.$aid);
		$criteria->addCondition('state=0');
		$a_deadhead_models=Deadhead_info::model()->findAll($criteria);
		foreach($a_deadhead_models as $key=>$val){
			$c_deadhead=new Deadhead_info;
			$c_deadhead->origin=$val->origin;
			$c_deadhead->destination=$val->destination;
			$c_deadhead->mileage=$val->mileage;
			$c_deadhead->driving_circuit=$val->driving_circuit;
			$c_deadhead->fuel_name=$val->fuel_name;
			$c_deadhead->gas_fee=$val->gas_fee;
			$c_deadhead->bridge_charge=$val->bridge_charge;
			$c_deadhead->deadhead_reason=$val->deadhead_reason;
			$c_deadhead_models[]=$c_deadhead;
		}
		return $a_deadhead_models;
	}
}
